package com.xncoding.websocket.WebMvc.demoStomp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    //废弃
 /*   @Bean
    public CustomHandshakeHandler getCustomHandshakeHandler() {
        return new CustomHandshakeHandler();
    }*/

    @Autowired
    private WSTokenInterceptor wsTokenInterceptor;

    @Autowired
    private StompErrorHandler stompErrorHandler;

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws") // 设置端点
                //.addInterceptors(getCustomHandshakeHandler()) // 设置握手处理器。废弃
                .setAllowedOriginPatterns("*"); //跨域
        //.withSockJS(); // 启用SockJS 如果页面使用了SocketJS，这里就要配置。当然前缀ws://就会变成http://
        registry.setErrorHandler(stompErrorHandler);//异常处理类
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //服务端向客户端发心跳的线程,如果不设置，页面与服务端就不会互发心跳
        ThreadPoolTaskScheduler tts=new ThreadPoolTaskScheduler();
        tts.setPoolSize(1);
        tts.setThreadNamePrefix("ws-heartbeat-thread-");
        tts.initialize();
        //客户端接收服务端发送消息地址的前缀  setHeartbeatValue是设置PING、PONG心跳间隔默认都是10秒
        registry.enableSimpleBroker("/topic").setHeartbeatValue(new long[]{10000,10000}).setTaskScheduler(tts);

        //客户端给服务端发消息的地址前缀
        //registry.setApplicationDestinationPrefixes("/app");
        registry.setUserDestinationPrefix("/user");//指定用户发送（1对1）的地址前缀
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(wsTokenInterceptor);
    }
}